package com.skywolf.chem.customer.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.common.sysconfig.pojo.vo.PageVO;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.customer.entity.Customer;
import com.skywolf.chem.customer.entity.Signup;
import com.skywolf.chem.customer.param.CourseQueryParam;
import com.skywolf.chem.customer.param.CustomerParam;
import com.skywolf.chem.customer.param.UserDto;
import com.skywolf.chem.customer.service.ICustomerService;
import com.skywolf.chem.customer.service.ISignupService;
import com.skywolf.chem.live.param.CourseDto;
import com.skywolf.chem.tencent.service.ImService;
import com.skywolf.chem.utils.CryptUtil;
import com.skywolf.chem.utils.PhoneUtils;
import com.skywolf.chem.utils.RequestConstans;
import com.skywolf.chem.utils.sms.TXSendMsg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author 
 * @since 2020-11-29
 */
@RestController
@RequestMapping("/edu/customer")
@Api(value = "API个人中心相关接口", description = "API个人中心相关接口")
public class CustomerController {

    @Autowired
    ICustomerService customerService;

    @Autowired
    ISignupService signupService;

    @Autowired
    ImService imService;

    @ApiOperation(value = "获取IMSig",notes = "获取IMSig")
    @RequestMapping(value = "/imSig",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> imSig(HttpServletRequest request) {
        String uid = request.getHeader("uid");
        String sig = imService.getUseSig(uid,null);
        return RespData.success(sig);
    }

    @ApiOperation(value = "查询他人用户信息",notes = "查询他人用户信息")
    @RequestMapping(value = "/getUserinfo",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<UserDto> getUserinfo(HttpServletRequest request,@RequestParam(value = "uid",required = true) Long uid) {
//        String user_id = request.getHeader("uid");
        Customer customer = customerService.getById(Long.valueOf(uid));
        UserDto user = new UserDto();
        BeanUtils.copyProperties(customer,user);
        if(customer.getLoginTime()==null){
            customer.setLoginTime(LocalDateTime.now());
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formattedDateTime = customer.getLoginTime().format(formatter); // "1986-04-08 12:30"
        user.setLoginTime(formattedDateTime);
        return RespData.success(user);
    }

    @ApiOperation(value = "用户信息",notes = "用户信息")
    @RequestMapping(value = "/userinfo",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<UserDto> userinfo(HttpServletRequest request) {
        String uid = request.getHeader("uid");
        Customer customer = customerService.getById(Long.valueOf(uid));
        UserDto user = new UserDto();
        BeanUtils.copyProperties(customer,user);
        if(customer.getLoginTime()==null){
            customer.setLoginTime(LocalDateTime.now());
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String formattedDateTime = customer.getLoginTime().format(formatter); // "1986-04-08 12:30"
        user.setLoginTime(formattedDateTime);

        QueryWrapper<Signup> queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",Long.valueOf(uid));
        Integer count = signupService.count(queryWrapper);
        user.setCourseCount(count);
        return RespData.success(user);
    }

    @ApiOperation(value = "更新用户信息",notes = "更新用户信息")
    @RequestMapping(value = "/updateUser",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> updateUser(HttpServletRequest request,@RequestBody UserDto user) {
        String uid = request.getHeader("uid");
        Customer customer = new Customer();
        BeanUtils.copyProperties(user,customer);
        customer.setId(Long.valueOf(uid));
        customerService.updateById(customer);
        return RespData.success("success");
    }


    @ApiOperation(value = "更新用户密码短信",notes = "更新用户密码短信")
    @RequestMapping(value = "/updatePassWordMsg",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> updatePassWordMsg(HttpServletRequest request, @RequestBody CustomerParam param) {
        String uid = request.getHeader("uid");
        if(param==null || !PhoneUtils.phoneCheck(param.getPhone())){
            return RespData.failure(ResponseCodeEnum.PHONE_ERROR);
        }
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", param.getPhone());
        Customer user = customerService.getOne(queryWrapper);
        if(!uid.equals(user.getId()+"")){
            return RespData.failure(ResponseCodeEnum.ACCOUNT_NOT);
        }
        if(user != null && StringUtils.isBlank(user.getPassword())){
            return RespData.failure(ResponseCodeEnum.PHONE_NO_REG);
        }
        String code = PhoneUtils.getCode();
        Boolean bl = TXSendMsg.sendMsg(param.getPhone(), code,uid);
        if(!bl){
            return RespData.failResult("短信发送失败");
        }
        user.setCode(code);
        user.setCodeTime(LocalDateTime.now());
        customerService.updateById(user);
        return RespData.success("success");
    }

    @ApiOperation(value = "更新用户密码",notes = "更新用户密码")
    @RequestMapping(value = "/updatePassWord",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> updatePassWord(HttpServletRequest request, @RequestBody CustomerParam param) {
        String uid = request.getHeader("uid");
        Customer user = customerService.getById(Long.valueOf(uid));
        Long nowTime = System.currentTimeMillis()/1000;
        Long codeTime = user.getCodeTime().toEpochSecond(ZoneOffset.of("+8"));
        if(nowTime-codeTime>300){
            return RespData.failure(ResponseCodeEnum.CODE_EXPIRE);
        }
        if(StringUtils.isBlank(param.getPassword())){
            return RespData.failure(ResponseCodeEnum.PWD_NEW);
        }
        user.setPassword(CryptUtil.encryptAES128(param.getPassword(), RequestConstans.decode_pwd));
        customerService.updateById(user);
        return RespData.success("success");
    }

    @ApiOperation(value = "已学习/已报名课程列表",notes = "已学习/已报名课程列表")
    @RequestMapping(value = "/myCourse",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<CourseDto> myCourse(HttpServletRequest request,@RequestBody @Validated CourseQueryParam queryParam) {
        Long uid = Long.valueOf(request.getHeader("uid"));
        PageVO<CourseDto> page = signupService.pageCourseList(queryParam,uid);
        return RespData.success(page);
    }





}
